﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace FlashPay.Admin.Controllers
{
    using FlashPay.Admin.ViewModels.Role;
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request.Authorize;
    using FlashPay.Entity.Request.Role;
    using FlashPay.Entity.Response.Company;
    using FlashPay.Entity.Response.Role;
    using FlashPay.Entity.Response.User;
    using FlashPay.Service.Interface;
    using FlashPay.Util;
    using Microsoft.AspNetCore.Http;

    /// <summary>
    /// 角色控制器
    /// </summary>
    public class RoleController : BaseController
    {
        #region 注入
        /// <summary>
        /// 用户业务接口
        /// </summary>
        private readonly SysRoleService _sysRoleService;


        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="sysRoleService">角色业务接口</param>
        public RoleController(IAuthenticate<TicketResponse> _manage, IHttpContextAccessor _accessor, SysRoleService sysRoleService):base(_manage, _accessor)
        {
            _sysRoleService = sysRoleService;
        }
        #endregion

        /// <summary>
        /// 根据编号获取角色
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.Role0001)]
        public JsonResult Get(int id) {
            //输出
            var response = new JResult<RoleResponse>()
            {
                Success = false
            };

            var model = _sysRoleService.Get(id);
            if (model != null) {
                response.Data = model;
                response.Success = true;
            }
            return Json(response);
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        [AuthorizeFilter(AuthCode.Role0001,AuthCode.AllowEdit, AuthCode.CompanyMonth0001, AuthCode.CompanyYear0001, AuthCode.CompanyBankCard0001, AuthCode.PaymentRecord0001, AuthCode.PaymentCard0001,AuthCode.PaymentInterface0001)]
        public JsonResult GetCompany()
        {
            var response = new JResult<List<CompanyResponse>>()
            {
                Success = false
            };
            try
            {
                //所属公司
                if (_manage.data.CompanyID <= 0)
                {
                    throw new Exception("所属公司不存在!");
                }
                
                response.Data = _sysRoleService.GetCompany(this._manage.data.CompanyID,2);
                response.Success = true;
            }
            catch (Exception ex) {
                response.ErrorMessage = ex.Message;
            }
            
            return Json(response);
        }


        /// <summary>
        /// 公司搜索
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public JsonResult CompanySearch(string companyName)
        {
            var response = new JResult<List<CompanyResponse>>()
            {
                Success = false
            };
            try
            {
                //所属公司
                if (_manage.data.CompanyID <= 0)
                {
                    throw new Exception("所属公司不存在!");
                }

                companyName = WebUtil.FilterChar(companyName);

                var companys = _sysRoleService.GetCompany(this._manage.data.CompanyID,2);

                if (companys != null && companys.Any() && !string.IsNullOrEmpty(companyName))
                {
                    response.Data = companys.MyDistinct(p => p.CompanyName).Where(p => p.CompanyName.Contains(companyName)).ToList();
                }
                response.Success = true;
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 获取角色菜单权限树
        /// </summary>
        /// <param name="roleSysNo">角色编号</param>
        /// <returns>角色菜单权限树</returns>
        [AuthorizeFilter(AuthCode.Role0001)]
        public JsonResult GetMenuPermissionTree(int? roleSysNo)
        {
            if (roleSysNo.HasValue)
            {
                var list = _sysRoleService.GetMenuPermissionViewListByRoleSysNo(this._manage.data.UserPermission, this._manage.data.MType, roleSysNo.Value,_manage.data.UserID);
                return Json(list);
            }
            else {
                var list = _sysRoleService.GetMenuPermissionViewListByRole(this._manage.data.UserPermission, this._manage.data.MType,_manage.data.UserID);
                return Json(list);
            }
        }

        #region 新增、编辑
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AuthorizeFilter(AuthCode.Role0002, AuthCode.Role0003,AuthCode.AllowEdit)]
        public JsonResult GetAddOrEdit(int? id)
        {
            //输出
            var response = new JResult<RoleResponse>()
            {
                Success = false
            };
            if (id.HasValue)
            {
                var model = _sysRoleService.Get(id.Value);
                if (model != null)
                {
                    response.Data = model;
                    response.Success = true;
                }
            }
            return Json(response);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AuthorizeFilter(AuthCode.Role0002, AuthCode.Role0003, AuthCode.AllowEdit)]
        public JsonResult GetClone(int? id)
        {
            //输出
            var response = new JResult<RoleResponse>()
            {
                Success = false
            };
            if (id.HasValue)
            {
                var model = _sysRoleService.GetClone(_manage.data.CompanyID,id.Value);
                if (model != null)
                {
                    response.Data = model;
                    response.Success = true;
                }
            }
            return Json(response);
        }

        /// <summary>
        /// 角色保存或修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AuthorizeFilter(AuthCode.Role0002)]
        public JsonResult SaveOrEdit(SaveOrEditViewModel role, List<ViewModels.Role.AuthorizeViewModel> authorize, List<ViewModels.Role.AuthorizeViewModel> unselecteds)
        {
            //输出
            var response = new JResult<SysRole>()
            {
                Success = false
            };

            try
            {
                if (!ModelState.IsValid)
                {
                    var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();

                    return Json(new JResult()
                    {
                        Success = false,
                        ErrorMessage = message
                    });
                }

                //所属公司
                if (_manage.data.CompanyID <= 0)
                {
                    throw new Exception("所属公司不存在!");
                }

                var para = new RoleRequest()
                {
                    RId = role.RId,
                    RCompanyId = role.RCompanyId,
                    RName = role.RName,
                    CreateDate = DateTime.Now,
                    RStatus = role.RStatus,
                    CreateCid = _manage.data.CompanyID,
                    CreateUid = _manage.data.UserID
                };

                if (role.RId > 0) {
                    var model = _sysRoleService.Get(role.RId);
                    if (model == null) {
                        throw new Exception("修改的角色不存在!");
                    }

                    //当前公司的子公司
                    var companyIds = _sysRoleService.GetCompany(model.RCompanyId, 5).Select(p => p.CompanyID).ToList();
                    if (companyIds != null && companyIds.Any())
                    {
                        if (companyIds.Any(p => p == model.RCompanyId))
                        {
                            companyIds.Remove(model.RCompanyId);
                        }
                        para.CompanyIds = companyIds;
                    }
                }

                #region 选中
                var authorizes = new List<AuthorizeRequest>();

                if (authorize != null && authorize.Any())
                {
                    var permissionIds = new List<int>();

                    authorize.ForEach(item => {

                        authorizes.Add(new AuthorizeRequest()
                        {
                            AuthRid = item.AuthRid,
                            AuthPid = item.AuthPid,
                            AuthType = item.AuthType,
                        });
                    });
                }
                #endregion

                #region 未选中
                var unselectedAuthorizes = new List<AuthorizeRequest>();

                if (unselecteds != null && unselecteds.Any())
                {
                    var permissionIds = new List<int>();

                    unselecteds.ForEach(item => {

                        unselectedAuthorizes.Add(new AuthorizeRequest()
                        {
                            AuthRid = item.AuthRid,
                            AuthPid = item.AuthPid,
                            AuthType = item.AuthType,
                        });
                    });

                    para.authorizeRequests = unselectedAuthorizes;
                }
                #endregion

                //角色名称
                if (string.IsNullOrEmpty(role.RName))
                {
                    throw new Exception("角色名称不能为空!");
                }

                response = _sysRoleService.SaveOrEdit(para, authorizes, unselectedAuthorizes);
            }
            catch (Exception ex) {
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 克隆
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AuthorizeFilter(AuthCode.Role0002)]
        public JsonResult Clone(SaveOrEditViewModel role, List<AuthorizeViewModel> authorize)
        {
            //输出
            var response = new JResult<SysRole>()
            {
                Success = false
            };

            try
            {
                if (!ModelState.IsValid)
                {
                    var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();

                    return Json(new JResult()
                    {
                        Success = false,
                        ErrorMessage = message
                    });
                }

                //所属公司
                if (_manage.data.CompanyID <= 0)
                {
                    throw new Exception("所属公司不存在!");
                }

                var para = new RoleRequest()
                {
                    RId = role.RId,
                    RCompanyId = role.RCompanyId,
                    RName = role.RName,
                    CreateDate = DateTime.Now,
                    RStatus = role.RStatus,
                    CreateCid = _manage.data.CompanyID,
                    CreateUid = _manage.data.UserID
                };

                if (role.RId > 0)
                {
                    var model = _sysRoleService.Get(role.RId);
                    if (model == null)
                    {
                        throw new Exception("修改的角色不存在!");
                    }

                    //当前公司的子公司
                    var companyIds = _sysRoleService.GetCompany(model.RCompanyId, 2).Select(p => p.CompanyID).ToList();

                    if (model.RCompanyId == model.CreateCId)
                    {
                        //同级权限
                    }
                    else if (model.CreateCId == _manage.data.CompanyID)
                    {
                        //子公司权限
                        if (companyIds != null && companyIds.Any())
                        {
                            companyIds.Add(model.RCompanyId);
                            para.CompanyIds = companyIds;
                        }
                    }
                }

                #region 选中
                var authorizes = new List<AuthorizeRequest>();

                if (authorize != null && authorize.Any())
                {
                    var permissionIds = new List<int>();

                    authorize.ForEach(item => {

                        authorizes.Add(new AuthorizeRequest()
                        {
                            AuthRid = item.AuthRid,
                            AuthPid = item.AuthPid,
                            AuthType = item.AuthType,
                        });
                    });
                }
                #endregion

                //角色名称
                if (string.IsNullOrEmpty(role.RName))
                {
                    throw new Exception("角色名称不能为空!");
                }

                response = _sysRoleService.SaveOrEdit(para, authorizes, null);
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }
        #endregion

        /// <summary>
        /// 角色名字搜索
        /// </summary>
        /// <param name="query">参数</param>
        [AuthorizeFilter(AuthCode.Role0001)]
        public JsonResult RoleAutoSearch(SysRoleQuery query)
        {
            //输出
            var response = new JResult<List<RoleResponse>>()
            {
                Success = true
            };

            try
            {
                query.CurrentPageIndex = 1;
                query.PageSize = 10;
                query.CompanyId = _manage.data.CompanyID;
                query.RName = WebUtil.FilterChar(query.RName);

                var pager = _sysRoleService.GetPager(query);
                if (pager != null && pager.TData != null)
                {
                    var roleResponses = new List<RoleResponse>();

                    foreach (var item in pager.TData)
                    {
                        roleResponses.Add(new RoleResponse()
                        {
                            RId = item.RId,
                            RName = item.RName
                        });
                    }

                    response.Data = roleResponses;
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.Role0005)]
        public JsonResult Delete(int id)
        {
            //杈撳嚭
            var response = new JResult()
            {
                Success = false
            };
            response = _sysRoleService.Delete(id);

            return Json(response);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.Role0003)]
        public JsonResult UpdateStatus(int id,SByte status)
        {
            //输出
            var response = new JResult()
            {
                Success = false
            };

            response = _sysRoleService.UpdateStatus(id, status);

            return Json(response);
        }

        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>Json</returns>
        [AuthorizeFilter(AuthCode.Role0001, AuthCode.AllowEdit)]
        public JsonResult GetRoleList(SysRoleQuery query)
        {
            //输出
            var response = new JResult<List<SysRole>>()
            {
                Success = false
            };
            if (query.CompanyId == null || query.CompanyId <= 0)
            {
                query.CompanyId = _manage.data.CompanyID;
            }

            query.CreateCID = _manage.data.CompanyID;

            var list = _sysRoleService.GetList(query);
            if (list != null && list.Any()) {
                response.Data = list;
                response.Success = true;
            }

            return Json(response);
        }

        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>Json</returns>
        [AuthorizeFilter(AuthCode.Role0001, AuthCode.AllowEdit)]
        public JsonResult GetCompanyRole(SysRoleQuery query)
        {
            //输出
            var response = new JResult<List<SysRole>>()
            {
                Success = false
            };

            query.CompanyId = _manage.data.CompanyID;
            query.RoleCompanyId = query.RoleCompanyId;
            query.CreateUId = _manage.data.UserID;

            var list = _sysRoleService.GetRoleByCompanyId(query);
            if (list != null && list.Any())
            {
                response.Data = list.MyDistinct(s=>s.RId).ToList();
                response.Success = true;
            }

            

            return Json(response);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        [AuthorizeFilter(AuthCode.Role0001)]
        public JsonResult GetPager(SysRoleQuery query)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }

            //CompanyId从登录信息中取、这里占时写死
            query.CompanyId = ticketResponse.CompanyID;
            query.CreateCID = ticketResponse.CompanyID;
            query.CreateUId = ticketResponse.UserID;
            query.CompanyName = WebUtil.FilterChar(query.CompanyName);
            query.RName = WebUtil.FilterChar(query.RName);

            //获取分页列表
            var pager = _sysRoleService.GetPager(query);

            return Json(pager);
        }
    }
}